﻿Imports Kairyu.DCEngine
Imports System.Text


''' <summary>
''' インスタンス検索条件
''' </summary>
''' <remarks></remarks>
Public Class InstanceCondition
    Implements ICondition

    Private Sub New()
    End Sub

    Public Shared Function Create(instance As Object, props As IEnumerable(Of LiteralProperty))
        If instance Is Nothing Then Throw New ArgumentNullException("instance")
        If props Is Nothing Then Throw New ArgumentNullException("props")

        Dim c As New InstanceCondition
        c.Instance = instance
        For Each item In props
            c.LiteralProperties.Add(item)
        Next

        Return c
    End Function

    ''' <summary>
    ''' インスタンス
    ''' </summary>
    ''' <value></value>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Property Instance As Object

    Private _literalProperties As New List(Of LiteralProperty)
    ''' <summary>
    ''' リテラルプロパティリスト
    ''' </summary>
    ''' <value></value>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public ReadOnly Property LiteralProperties As IList(Of LiteralProperty)
        Get
            Return _literalProperties
        End Get
    End Property

    ''' <summary>
    ''' SQLを組み立てます
    ''' </summary>
    ''' <param name="setParameter"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function BuildSql(setParameter As Func(Of Object, String)) As String Implements ICondition.BuildSql
        If setParameter Is Nothing Then Throw New ArgumentNullException("setParameter")

        Dim s As New StringBuilder

        For Each item In Me.LiteralProperties
            'パラメータ値
            Dim val = item.GetLiteralValue(Instance)

            'パラメータ名
            Dim pname = setParameter.Invoke(val)

            '列名
            Dim colName = item.LiteralName

            s.AppendDelimiter(" AND ").AppendFormat("T0.{0} = {1}", colName, pname)
        Next

        'SQL文返却
        If Me.LiteralProperties.Count = 1 Then
            Return s.ToString
        Else
            Return "(" & s.ToString & ")"
        End If
    End Function

End Class